# -*- coding: utf-8 -*-

from odoo import models

from datetime import datetime, date
from marshmallow import fields

from ..utils.common import sanitize_html_field, convert_to_attachment_url, convert_to_video_url


class Integer(fields.Integer):
    def _serialize(self, value, attr, obj, **kwargs):
        if isinstance(value, models.BaseModel):
            value = value.id
        if value is False:
            value = None
        return super()._serialize(value, attr, obj, **kwargs)


class Str(fields.Str):
    def _serialize(self, value, attr, obj, **kwargs):
        if value is False:
            value = None
        return super()._serialize(value, attr, obj, **kwargs)


class Html(Str):
    def _serialize(self, value, attr, obj, **kwargs):
        if value:
            value = sanitize_html_field(value)
        return super()._serialize(value, attr, obj, **kwargs)

class AttachmentUrl(Str):
    def _serialize(self, value, attr, obj, **kwargs):
        if value:
            value = convert_to_attachment_url(value)
        else:
            value = False
        return super()._serialize(value, attr, obj, **kwargs)


class VideoUrl(Str):
    def __init__(self, *args, model_xmlid=None, filename_field=None, **kwargs):
        super().__init__(*args, **kwargs)
        assert model_xmlid, 'Must specify model_xmlid for VideoUrl field'
        assert filename_field, 'Must specify filename_field for VideoUrl field'
        self.model_xmlid = model_xmlid
        self.filename_field = filename_field

    def _serialize(self, value, attr, obj, **kwargs):
        if value:
            value = convert_to_video_url(obj.ids[0], self.model_xmlid, self.attribute or attr, self.filename_field)
        else:
            value = False
        return super()._serialize(value, attr, obj, **kwargs)


class Nested(fields.Nested):
    pass


class List(fields.List):
    def _deserialize(self, value, attr, data, **kwargs):
        if not isinstance(value, (list, tuple)):
            value = [value]
        return value


class Timestamp(Integer):
    def _serialize(self, value, attr, obj, **kwargs):
        if isinstance(value, datetime):
            value = value.timestamp()
        elif isinstance(value, date):
            value = datetime.combine(value, datetime.min.time()).timestamp()
        try:
            value = int(value)
        except:
            value = None
        return super()._serialize(value, attr, obj, **kwargs)
